Tugas Restful API pada Laravel

API

API (Application Programming Interface) merupakan sekumpulan aturan dan protokol yang memungkinkan aplikasi berbeda platform untuk berkomunikasi dan saling terintegrasi

Mengapa API Penting?

API (Application Programming Interface) adalah media untuk komunikasi antara aplikasi yang berbeda. Dalam era digital saat ini, hampir semua aplikasi modern menggunakan API untuk

• Integrasi dengan layanan pihak ketiga

• Memisahkan frontend dan backen

• Mendukung multiple platform (web, mobile, desktop)

• Memungkinkan microservices architecture

Konsep Dasar API

Agar lebih memahami konsep dasar API berikut analogi API pemesanan makanan pada restoran.

Komponen Utama API

Berikut merupakan ilustrasi komponen utama API

Jenis-jenis API

• Web API : Menggunakan protokol HTTP/HTTPS

• REST API: Mengikuti arsitektur REST

• GraphQL API: Query language untuk API

• SOAP API: Protocol berbasis XML

• Library API: Interface untuk library atau framework

• Operating System API: Interface dengan sistem operasi

• Database API: Interface untuk mengakses database

RESTful API

REST (Representational State Transfer) adalah arsitektur untuk merancang web services. REST bukan protokol atau standar, melainkan seperangkat prinsip desain.

Prinsip REST (Representational State Transfer)

• Client-Server Architecture

• Stateless

• Cacheable

• Uniform Interface

• Layered System

• Code on Demand

Langkah-langkah membuat API

Buat Projek Laravel Baru

Dengan mengetik kode berikut :

composer create-project laravel/laravel api-project

Membuat Migrasi Database

Dengan mengetik kode berikut :

php artisan make:migration create_products_table

Kemudian, ketik kode program berikut :

Schema::create('products', function (Blueprint $table) { 
                $table->id(); 
                $table->string('name'); 
                $table->text('description'); 
                $table->decimal('price', 10, 2); 
                $table->integer('stock'); 
                $table->timestamps(); 
            });

Jalankan migration dengan kode berikut :

php artisan migrate

Membuat Model

php artisan make:model Product

Kemudian, ketik kode program berikut :

class Product extends Model 
                { 
                    protected $fillable = [ 
                        'name', 'description', 'price', 'stock' 
                    ]; 
                     
                    protected $casts = [ 
                        'price' => 'decimal:2' 
                    ]; 
                } 

Membuat API Routes

Install API terlebih dahulu dengan kode berikut :

php artisan install:api

Ketik kode berikut di file routes/api.php

// routes/api.php
Route::apiResource('products', ProductController::class);

// manual:
Route::get('products', [ProductController::class, 'index']);
Route::post('products', [ProductController::class, 'store']);
Route::get('products/{product}', [ProductController::class, 'show']);
Route::put('products/{product}', [ProductController::class, 'update']);
Route::delete('products/{product}', [ProductController::class, 'destroy']);

Membuat API Controller

Buka terminal lalu jalankanlah kode berikut ini

php artisan make:controller ProductController --api

Ketik kode berikut pada controller :

class ProductController extends Controller 
                { 
                    public function index() 
                    { 
                        $products = Product::all(); 
                        return response()->json([ 
                            'status' => 'success', 
                            'data' => $products 
                        ]); 
                    } 
                     
                    public function store(Request $request) 
                    { 
                        $validated = $request->validate([ 
                            'name' => 'required|string|max:255', 
                            'description' => 'required|string', 
                            'price' => 'required|numeric|min:0', 
                            'stock' => 'required|integer|min:0' 
                        ]); 
                         
                        $product = Product::create($validated); 
                         
                        return response()->json([ 
                            'status' => 'success', 
                            'message' => 'Product created successfully', 
                            'data' => $product 
                        ], 201); 
                    } 
                     
                    public function show(Product $product) 
                    { 
                        return response()->json([ 
                            'status' => 'success', 
                            'data' => $product 
                        ]); 
                    } 
                     
                    public function update(Request $request, Product $product) 
                    { 
                        $validated = $request->validate([ 
                            'name' => 'sometimes|string|max:255', 
                            'description' => 'sometimes|string', 
                            'price' => 'sometimes|numeric|min:0', 
                            'stock' => 'sometimes|integer|min:0' 
                        ]); 
                         
                        $product->update($validated); 
                         
                        return response()->json([ 
                            'status' => 'success', 
                            'message' => 'Product updated successfully', 
                            'data' => $product 
                        ]); 
                    } 
                     
                    public function destroy(Product $product) 
                    { 
                        $product->delete(); 
                         
                        return response()->json([ 
                            'status' => 'success', 
                            'message' => 'Product deleted successfully' 
                        ]); 
                    } 
                }

API Resource

Salah satu fitur API Resource adalah kemampuan untuk mengubah model data atau kumpulan menjadi format JSON yang konsisten dan mudah dikustomisasi untuk tanggapan API. API Resource berfungsi sebagai lapisan transformasi antara model Eloquent dan tanggapan JSON yang dikirim ke client, sehingga dapat digunakan untuk Mengatur format output JSON, menyembunyikan kolom sensitif, menambahkan kolom komputasi, dan menghasilkan tanggapan yang konsisten

1. Membuat Resource

php artisan make:resource ProductResource

Kemudian, isi dengan kode program berikut :

class ProductResource extends JsonResource 
                    { 
                        public function toArray($request) 
                        { 
                            return [ 
                                'id' => $this->id, 
                                'name' => $this->name, 
                                'description' => $this->description, 
                                'price' => $this->price, 
                                'stock' => $this->stock, 
                                'created_at' => $this->created_at->format('Y-m-d H:i:s'), 
                                'updated_at' => $this->updated_at->format('Y-m-d H:i:s') 
                            ]; 
                        } 
                    }

2. Menggunakan Resource di Controller

Mengubah method index dan show menggunakan API Resource dengan mengetik kode berikut :

public function index() 
                    { 
                        $products = Product::all(); 
                        return ProductResource::collection($products); 
                    } 
                      
                    public function show(Product $product) 
                    { 
                        return new ProductResource($product); 
                    }

Validasi dan error Handling

Form Request Validation

php artisan make:request StoreProductRequest

Kemudian ketikkan kode berikut pada app/Http/Requests/StoreProductRequest.php

class StoreProductRequest extends FormRequest 
                    { 
                        public function authorize() 
                        { 
                            return true; 
                        } 
                         
                        public function rules() 
                        { 
                            return [ 
                                'name' => 'required|string|max:255', 
                                'description' => 'required|string', 
                                'price' => 'required|numeric|min:0', 
                                'stock' => 'required|integer|min:0' 
                            ]; 
                        } 
                         
                        public function messages() 
                        { 
                            return [ 
                                'name.required' => 'Nama produk wajib diisi', 
                                'price.min' => 'Harga tidak boleh negatif' 
                            ]; 
                        } 
                    }

Global Exception Handler

Tambahkan kode program berikut pada app/Exceptions/Handler.php untuk menanggani Exception

public function render($request, Throwable $exception)
                    {
                     if ($request->wantsJson()) {
                     if ($exception instanceof ValidationException) {
                     return response()->json([
                     'status' => 'error',
                     'message' => 'Validation failed',
                     'errors' => $exception->errors()
                     ], 422);
                     }
                     
                     if ($exception instanceof ModelNotFoundException) {
                     return response()->json([
                     'status' => 'error',
                     'message' => 'Resource not found'
                     ], 404);
                     }
                     }
                     
                     return parent::render($request, $exception);
                    }

Mengakses API Products dengan Postman

1. Download Postman pada link officialnya

2. Buka projek laravel tadi lalu ketikkan kode berikut :

php artisan serve

3. Mengambil semua products dengan method GET dan URL http://127.0.0.1:8000/api/products

Jika berhasil :

4. Menambahkan products dengan method POST dan URL http://127.0.0.1:8000/api/products/

Body (JSON)

{
    "name": "Smartphone Android",
    "description": "Smartphone dengan kamera 108MP dan RAM 8GB",
    "price": 4500000.00,
    "stock": 25
}

Jika Berhasil akan muncul seperti ini :

5. Mengambil Product Berdasarkan ID

Method: GET

URL: http://localhost:8000/products/{id}

Contoh: http://localhost:8000/products/1

6. Update product

Method: PUT

URL: http://localhost:8000/products/{id}

Contoh: http://localhost:8000/products/1

Body (JSON)

{
                    "name": "Laptop Gaming Updated",
                    "description": "Laptop gaming dengan spek tinggi dan SSD 1TB",
                    "price": 16500000.00,
                    "stock": 8
                   }

7. Hapus Product

Method: DELETE

URL: http://localhost:8000/products/{id}

Contoh: http://localhost:8000/products/1